<?php

namespace App\Http\Controllers\Admin;

use App\Events\UserLogin;
use App\Events\UserLogout;
use App\Http\Controllers\Controller;
use App\Http\Requests\UsersRequest;
use App\Utils\CodeEnumUtils;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

/**
 * 登录控制器
 * Author: Albert3306
 * Date: 2020/6/11
 * @package App\Http\Controllers\Admin
 */
class LoginController extends Controller
{
    /**
     * 添加路由过滤中间件
     */
    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'getLogout']);
    }

    /**
     * 登录页
     * Author: Albert3306
     * Date: 2020/6/11
     * @return Application|Factory|View
     */
    public function getLogin()
    {
        return view('admin.login')->with(['title' => '登录']);
    }

    /**
     * 登录数据提交
     * Author: Albert3306
     * Date: 2020/6/11
     * @param UsersRequest $request
     * @return JsonResponse
     */
    public function postLogin(UsersRequest $request)
    {
        // 获取认证凭证
        $where = $request->only('username', 'password');
        $where['status'] = 1;

        // 验证登陆
        if (Auth::guard('admin')->attempt($where)) {
            dd(auth('admin'));
            // 触发登录事件
            @event(new UserLogin(auth('admin')->user()));

            // 设置返回信息
            $code = 200;
        } else {
            $code = 1004;
        }

        // 返回数据
        return CodeEnumUtils::response($code);
    }

    /**
     * 退出登录
     */
    public function getLogout()
    {
        if (auth('admin')->user()) {
            @event(new UserLogout(auth('admin')->user()));  //触发登出事件
            Auth::guard('admin')->logout();
        }
        return redirect()->to(url('admin/login'));
    }
}
